package cn.edu.gzasc.registration.controller;


import cn.edu.gzasc.registration.dto.ResponseDto;
import cn.edu.gzasc.registration.entity.User;
import cn.edu.gzasc.registration.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

import static javax.security.auth.callback.ConfirmationCallback.OK;


@RestController
@RequestMapping(path="/api", produces = {MediaType.APPLICATION_JSON_VALUE})
@AllArgsConstructor
@Validated
@CrossOrigin
public class UserApiController {


    private UserRepository userRepository;

    @PostMapping("/user")
    public ResponseEntity<User> createUser(@Validated @RequestBody User user) {
        userRepository.save(user);
        return ResponseEntity.ok(user);
    }

    @GetMapping("/users")
    public ResponseEntity<List<User>> listAll(){
        return ResponseEntity.ok(userRepository.findAll());
    }

    @GetMapping("/users/{id}")
    public ResponseEntity<User> fetchUserById(@PathVariable int id) {
        Optional<User> user = userRepository.findById((long) id);
        return ResponseEntity.ok(user.orElse(null));
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<ResponseDto> deleteUserById(@PathVariable int id) {

        userRepository.deleteById((long)id);
        return ResponseEntity.status(200).body(new ResponseDto("200", "success"));
    }

    @PutMapping("/users")
    public ResponseEntity<ResponseDto> updateUser(@Validated @RequestBody User user) {
        userRepository.save(user);
        return ResponseEntity.ok(new ResponseDto("200", "success"));
    }

}
